<!--
 * @Author: ybf
 * @Date: 2023-02-21 15:31:51
 * @LastEditTime: 2023-02-22 10:43:19
 * @Description: 描述
 * Copyright (c) 2023 by 慧能分享, All Rights Reserved.
-->
<template>
  <div class="powerGeneration">
    <!-- <nu-col :span="24" style="height: calc(130px - 20px)"> -->
    <!-- <nutbTitle title="日发电计划考核详情"></nutbTitle> -->
    <NuVerifyForm :model="formData" ref="formData" label-width="100px" class="searchForm" @searchForm="searchForm"
      :buttons="fyButtons">
      <NuformItem label="日期" prop="checkDate" width="320px" :rules="[{ required: true, message: '日期不能为空' }]">
        <el-date-picker v-model="formData.checkDate" type="date" placeholder="请选择日期" style="width: 100%"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </NuformItem>
      <div class="btnBox">
        <nu-button type="primary" class="searchButton" @click="searchLine">搜索</nu-button>
        <nu-button class="searchButton" @click="clearParams">清除</nu-button>
        <nu-button class="searchButton" @click="exportTable">导出</nu-button>
        <nu-button class="searchButton" v-print="printOption">打印</nu-button>
      </div>
    </NuVerifyForm>
    <!-- </nu-col> -->
    <div class="line"></div>
    <!-- <nu-col :span="24" style="width: 100%; height: calc(100% - 130px - 20px)"> -->
    <nu-row class="row" :gutter="20">
      <nu-col :span="5" class="col">
        <nuTree v-model="currentLivingObj.id" :options="treeData" :props="defaultProps" @onClickNode="handleNodeClick">
        </nuTree>
      </nu-col>
      <nu-col :span="19" class="col">
        <nu-echarts width="auto" height="calc((100vh - 270px) - 260px)" :option="lineOption" class="echarts" style="
            margin: auto;
            margin-top: 0px;
            margin-left: 30px;
            margin-right: 30px;
            padding: 20px 0 0 0;
          " v-if="isEchart"></nu-echarts>
        <!-- <div class="editBtn">
          <el-button type="text" @click="editTable()" v-if="!isEdit">数据手动调整</el-button>
          <el-button type="text" @click="editTable()" v-if="isEdit">保存且返回</el-button>
        </div> -->
        <el-table size="small" :data="dataSource" highlight-current-row height="260" show-summary
          :summary-method="getSummaries" style="width: 100%;"
          :default-expand-all="options.expand == undefined ? true : options.expand" :default-sort="options.defaultSort"
          :empty-text="options.emptyText || '暂无数据'">
          <el-table-column prop="time" label="时段" align="center">
          </el-table-column>
          <el-table-column prop="nodeName" label="节点名称" align="center">
          </el-table-column>
          <el-table-column prop="energySchedule" label="调度计划电量（MWh）" align="center" width="160">
            <template slot-scope="scope">
              <span v-if="!isEdit">{{ scope.row.energySchedule }}</span>
              <el-input v-if="isEdit" size="mini" v-model="scope.row.energySchedule"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="channelName" label="下发通道" align="center">
          </el-table-column>
          <el-table-column prop="energyAccumulate" label="实发电量（MWh）" align="center">
            <template slot-scope="scope">
              <span v-if="!isEdit">{{ scope.row.energyAccumulate }}</span>
              <el-input v-if="isEdit" size="mini" v-model="scope.row.energyAccumulate"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="energyBias" label="偏差电量（MWh）" align="center">
            <template slot-scope="scope">
              <span v-if="!isEdit">{{ scope.row.energyBias }}</span>
              <el-input v-if="isEdit" size="mini" v-model="scope.row.energyBias"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="unchcekFlag" label="是否免考核" align="center">
          </el-table-column>
          <el-table-column prop="uncheckReason" label="免考核原因" align="center">
          </el-table-column>
          <el-table-column prop="energyCheck" label="考核电量（MWh）" align="center">
            <template slot-scope="scope">
              <span v-if="!isEdit">{{ scope.row.energyCheck }}</span>
              <el-input v-if="isEdit" size="mini" v-model="scope.row.energyCheck"></el-input>
            </template>
          </el-table-column>
        </el-table>
        <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSourceAll" :options="optionsPrint"
          style="position: absolute;left: -5000px;z-index: -100;opacity: 0;">
        </NuTableList>
      </nu-col>
    </nu-row>
    <!-- </nu-col> -->
  </div>
</template>
    
<script>
import nuCol from "@/components/base/col.vue";
import nutbTitle from "@/components/base/tableTitle.vue";
import nuEcharts from "@/components/base/echarts";
import NuVerifyForm from "@/components/verify-form";
import NuformItem from "@/components/verify-form/form-item.vue";
import nuInput from "@/components/base/input";
import nuSelect from "@/components/base/select";
import nuButton from "@/components/base/button";
import NuTableList from "@/components/tableList/TableFormList";
import nuRow from "@/components/base/row.vue";
import nuTree from "@/components/base/tree";
import { getDateTime } from "@/utils/ruoyi";
import * as echarts from "echarts";
import axios from "axios";
export default {
  name: "powerGeneration",
  components: {
    nuCol,
    nutbTitle,
    nuEcharts,
    NuVerifyForm,
    NuformItem,
    nuInput,
    nuSelect,
    nuButton,
    NuTableList,
    nuRow,
    nuTree,
  },
  data() {
    return {
      formData: {
        checkDate: "",
      },
      fyButtons: [],
      isEdit: false,
      isEchart: true,
      lineOption: {
        color: ["#40b0e2", "#69e5c1", "#626b90", "#a0a7e5"],
        title: {
          text: "",
          left: "0",
          textStyle: {
            fontWeight: "600",
            fontSize: '14'
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        xAxis: {
          type: "category",
          data: [],
        },
        yAxis: {
          type: "value",
          name: "MWh",
        },
        grid: {
          left: "3%",
          right: "3%"
        },
        series: [
          {
            name: "",
            data: [],
            type: "line",
            showAllSymbol: true,
            symbolSize: 0,
            smooth: false,
          },
          {
            name: "",
            data: [],
            type: "line",
            showAllSymbol: true,
            symbolSize: 0,
            smooth: false,
          },
        ],
      },
      dataSource: [],
      dataSourceAll: [],
      columns: [
        {
          label: "时段",
          prop: "time",
        },
        {
          label: "节点名称",
          prop: "nodeName",
        },
        {
          label: "调度计划电量（MWh）",
          prop: "energySchedule"
        },
        {
          label: "下发通道",
          prop: "channelName",
        },
        {
          label: "实发电量（MWh）",
          prop: "energyAccumulate",
        },
        {
          label: "偏差电量（MWh）",
          prop: "energyBias",
        },
        {
          label: "是否免考核",
          prop: "unchcekFlag",
        },
        {
          label: "免考核原因",
          prop: "uncheckReason",
        },
        {
          label: "考核电量（MWh）",
          prop: "energyCheck",
        },
      ],
      options: {
        "default-expand-all": true,
        "element-loading-background": "rgba(225,239,242)",
        "element-loading-text": "数据正在加载中",
        "row-key": "pid",
        "header-cell-style": {
          background: "rgba(105, 159, 209, 0.7)",
          color: "#fff",
          fontWeight: "bold",
          fontsize: "16px",
        },
        isNoSetHeight: true,
        height: "300px",
      },
      treeData: [],
      defaultProps: {
        parent: "parentId", // 父级唯一标识
        value: "id", // 唯一标识
        label: "name", // 标签显示
        children: "children", // 子级
      },
      currentLivingObj: { id: "" },
      tableEndData: {
        totalTitle: "全天统计",
        totalName: "通道1",
      },
      printOption: {
        id: "multipleTable",
        preview: true,
        previewTitle: "预览",
        popTitle: "",
        extraHead: "",
        extraCss: `<meta http-equiv='Content-Language' content='zh-cn'/>`
      },
      optionsPrint: {
        'row-key': 'pid',
        height: '100vh',
        tId: 'multipleTable',
        style: 'width:1000px'
      },
      sumObj: {}
    };
  },
  created() { },
  mounted() {
    this.formData.checkDate = getDateTime("day");
    this.getTreeData();
  },
  methods: {
    /**
     * 查询
     */
    searchLine() {
      this.$refs["formData"].searchForm("form");
    },
    /**
     * form组件内置查询事件
     */
    searchForm(val) {
      if (val) {
        this.getPowerGenerationLineData();
      }
    },
    /**
     * 类型change事件
     */
    typeChange() { },
    /**
     * 清除数据
     */
    clearParams() {
      this.resetForm("formData");
    },
    /**
     * 重置表单
     */
    resetForm(formName) {
      this.$refs[formName].resetForm("form");
      for (let k in this[formName]) {
        if (
          Object.prototype.toString.call(this[formName][k]) == "[object String]"
        ) {
          this[formName][k] = "";
        } else if (
          Object.prototype.toString.call(this[formName][k]) == "[object Array]"
        ) {
          this[formName][k] = [];
        } else if (
          Object.prototype.toString.call(this[formName][k]) == "[object Number]"
        ) {
          this[formName][k] = "";
        }
      }
    },
    /**
     * 导出
     */
    exportTable() {
      let postData = {
        ...this.formData,
        nodeName: this.currentLivingObj.name,
        bidUnitId: this.currentLivingObj.level == 2 ? this.currentLivingObj.id : '',
        pId: this.currentLivingObj.level == 1 ? this.currentLivingObj.id : '',
      };
      for (let k in postData) {
        if (!postData[k]) {
          delete postData[k]
        }
      }
      this.getDownload(window.api.checkScheduleDayDetailsExportFile, {
        ...postData
      }, `日发电计划考核详情.xlsx`)
    },
    /**
     * 获取柱图数据
     */
    getPowerGenerationLineData() {
      // if (!this.currentLivingObj?.id || this.currentLivingObj.level == 0) {
      //   this.$message({
      //     type: "info",
      //     message: "请先选择设备",
      //   });
      //   return false;
      // }
      let postData = {
        ...this.formData,
        nodeName: this.currentLivingObj.name,
        bidUnitId: this.currentLivingObj.level == 2 ? this.currentLivingObj.id : '',
        pId: this.currentLivingObj.level == 1 ? this.currentLivingObj.id : '',
      };
      for (let k in postData) {
        if (
          postData[k] &&
          Object.prototype.toString.call(postData[k]) == "[object String]"
        ) {
          postData[k] = postData[k].toString().trim();
        }
        if (!postData[k]) {
          delete postData[k]
        }
      }
      let xAxis = [];
      this.$httpGet(window.api.getCheckScheduleDayDetails, postData)
        .then((res) => {
          if (res.code == 200) {
            this.isEchart = false;
            xAxis = res.data.timeXAxis
            this.lineOption.title.text =
              this.currentLivingObj.name + "发电计划日考核电量";
            this.lineOption.xAxis.data = xAxis;
            this.lineOption.series[0].data = res.data.energyBiasYAxis;
            this.lineOption.series[1].data = res.data.energyCheckYAxis;
            this.lineOption.series[0].name = "偏差电量";
            this.lineOption.series[1].name = "考核电量";
            this.dataSourceAll = res.data.tableData
            let d = JSON.parse(JSON.stringify(res.data.tableData))
            if (d.length) {
              if (d[d.length - 1].time.indexOf('统计') > -1) {
                this.sumObj = JSON.parse(JSON.stringify(d[d.length - 1]))
                if (Object.keys(this.sumObj).length) {
                  d.splice(d.length - 1, 1)
                }
              }
            }
            this.dataSource = d;
            this.$nextTick(() => {
              this.isEchart = true;
            });
          } else {
            this.dataSource = [];
          }
        })
        .catch((err) => {
          this.dataSource = [];
        });
    },
    editTable() {
      this.isEdit = !this.isEdit
      if (this.isEdit == false) {
        console.log(this.dataSource)
      }
    },
    /**
     * 列表最后一行合计
     */
    getSummaries(param) {
      const { columns, data } = param;
      let sums = [];
      let obj = this.sumObj
      columns.forEach((column, index) => {
        if (Object.keys(obj).length) {
          sums[index] = obj[column.property];
        }
        return false
        // if (index === 0) {
        //   sums[index] = obj[column.property];
        //   return;
        // }
        // const values = data.map((item) => Number(item[column.property]));
        // if (!values.every((value) => isNaN(value))) {
        //   sums[index] = values.reduce((prev, curr) => {
        //     const value1 = Number(prev);
        //     const value = Number(curr);
        //     let aaa = null;
        //     if (!isNaN(value)) {
        //       aaa = (value1 + value).toFixed(2)
        //       return aaa;
        //     } else {
        //       return 0.00;
        //     }
        //   }, 0);
        //   //   sums[index] += " 元";
        // } else {
        //   if (index === 1) {
        //     sums[index] = this.tableEndData.totalName;
        //   } else {
        //     sums[index] = '-'
        //   }
        // }
      });
      return sums;
    },
    /**
     * tree节点单击
     */
    handleNodeClick(item, data) {
      this.currentLivingObj = item;
      this.currentLivingObj["level"] = data.level;
      this.searchLine()
    },
    //获取树形控件
    getTreeData() {
      this.$httpGet(window.api.getCheckTree, { treeType: 1 })
        .then((res) => {
          if (res.code == 200) {
            let obj = null;
            this.treeData.push(res.data);
            res.data.children.forEach((item) => {
              if (item?.id && !obj) {
                obj = item;
                return false;
              }
            });
            this.currentLivingObj = obj;
            this.currentLivingObj["level"] = 2;
            this.currentLivingObj.id = obj.id;
            this.getPowerGenerationLineData();
          } else {
          }
        })
        .catch((err) => { });
    },
  },
};
</script>
    
<style scoped lang="scss">
.powerGeneration {
  height: 100%;
}

.searchForm {
  // height: calc(100% - 40px);
  display: flex;
  align-items: center;
  position: relative;
}

.btnBox {
  display: flex;
  float: right;
  z-index: 10;
  position: absolute;
  top: 15px;
  right: 10px;
}

.row {
  height: calc(100% - 90px);
  width: 100%;
}

.col {
  height: 100%;
}

.el-tree {
  height: calc(100% - 10px);
  padding: 10px;
  margin: 0 0 0 10px;
}

.el-tree ::v-deep {
  .el-tree-node__content {
    position: relative;
  }

  //竖线
  .el-tree-node:last-child>.el-tree-node__content::before {
    content: "";
    width: 1px;
    height: 10000px;
    border-width: 1px;
    border-left: 1px solid #52627c;
    position: absolute;
    margin-left: -9px;
    bottom: 13px;
  }

  //横线
  .el-tree-node__children .el-tree-node__content::after {
    content: "";
    width: 13px;
    height: 1px;
    border-width: 1px;
    border-top: 1px solid #52627c;
    position: absolute;
    margin-left: -9px;
  }

  .el-tree-node__content>.el-tree-node__expand-icon {
    padding: 6px 3px;
  }

  .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-icon-caret-right:before {
    background: url("../../assets/images/tree_1.png") no-repeat 0;
    content: "";
    display: block;
    width: 16px;
    height: 16px;
    font-size: 16px;
    background-size: 16px;
  }

  //有子节点 且已展开
  .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
    background: url("../../assets/images/tree_2.png") no-repeat 0;
    content: "";
    display: block;
    width: 16px;
    height: 16px;
    font-size: 16px;
    background-size: 16px;
  }

  //没有子节点
  .el-tree-node__expand-icon.is-leaf::before {
    background: url("../../assets/images/tree_2.png") no-repeat 0;
    content: "";
    display: block;
    width: 16px;
    height: 16px;
    font-size: 16px;
    background-size: 16px;
  }

  /* 点击树结构项的选中颜色 */
  .el-tree--highlight-current .is-current.el-tree-node>.el-tree-node__content {
    background-color: #99ccff !important;
  }
}

.editBtn {
  text-align: right;
}

.el-table {
  overflow: visible !important;
}

::v-deep .el-form-item__content {
  height: 34px;
}
</style>
    
    